package we.logger.scribe;

import java.util.ArrayList;
import java.util.List;

import we.common.CCommonHandler;

import we.config.CConfigHandler;

import we.logger.ILogController;

import org.apache.scribe.LogEntry;
import org.apache.scribe.scribe.Client;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;


public class CScribeLogController implements ILogController {
    public CScribeLogController() {
    }

    /**
     * Hàm thực hiện việc write log tới scribe server
     * @param game mã game, dùng để xác định file config của game này
     * @param mode dùng để phân biệt log action và log error
     * @param data nội dung cần log
     */
    public void writeLog(LogMode mode, String data) {
        TSocket socket;
        TTransport transport;
        TProtocol protocol;
        Client client;
        List<LogEntry> entrys = new ArrayList<LogEntry>();
        entrys.add(new LogEntry(CConfigHandler.instance().get(mode.value() +
                                                            "_log_category"),
                                data));
        try {
            socket =
                    new TSocket(CConfigHandler.instance().get("lservers"), 1463);
            transport = new TFramedTransport(socket);
            protocol = new TBinaryProtocol(transport, false, false);
            client = new Client(protocol, protocol);
            transport.open();
            client.Log(entrys);
            transport.close();
        } catch (TTransportException e) {
            CCommonHandler.writeErrLog(e);
        } catch (TException e) {
            CCommonHandler.writeErrLog(e);
        }
    }
}
